package cn.com.callback;

import groovy.json.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.com.elite.EliteBean;
import java.text.SimpleDateFormat;
import net.sf.json.JSONObject;
import net.sf.json.JSONArray;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.elite.Util;

import java.util.concurrent.TimeUnit;
import cn.com.kh.getProperty;
import cn.com.kh.PDFHelper;

public class apiPDFDeal implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiPDFDeal.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        log.debug("apiPDFDeal Start:" + request);
        response.setCharacterEncoding("UTF-8");

        String callJson = "";
        String reJson = "";

        BufferedReader iny = null;

        // 获取调用参数信息
        InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
        iny = new BufferedReader(reader);
        String line;
        while ((line = iny.readLine()) != null) {
            callJson += line;
        }

        log.debug("apiPDFDeal callJson:" + callJson);

        //初始化接收参数
        String ismerge = "";
        String ismark = "";
        String markpic = "";
        int x_axis = 0;
        int y_axis = 0;
        int zoom = 0;
        List sourceList = new ArrayList();
        String id = "";
        String url = "";

        //初始化替换参数
        String webPath = "/ngs/jss";

        //定义临时处理变量
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        String PDFTempPath = getProperty.get("PDFPath") + dateFormat.format(calendar.getTime()).toString() + "/";
        //文件夹路径是否存在不存在则创建
        File dir = new File(PDFTempPath);
        if (!dir.exists()) {
            log.debug("创建所需路径:" + PDFTempPath);
            dir.mkdirs();
        }

        String fileNo = "";
        String convPath = "";
        String markPath = "";
        boolean convResult = false;
        boolean markResult = false;
        boolean combResult = false;
        JSONArray reValue = new JSONArray();
        List<String> combinList = new ArrayList<>();


        try {
            //初始化Json
            def root = new JsonSlurper().parseText(callJson);
            ismerge = root.ismerge;
            ismark = root.ismark;
            sourceList = root.value;

            log.debug("解析参数信息:" + " ismerge:" + ismerge + " ismark:" + ismark + " sourceList:" + sourceList.size());

            if (ismark.equals("1")) {
                markpic = root.markinfo.markpic;
                x_axis = root.markinfo.x_axis;
                y_axis = root.markinfo.y_axis;
                zoom = root.markinfo.zoom;
                log.debug("解析水印参数信息:" + " markpic:" + markpic + " x_axis:" + x_axis + " y_axis:" + y_axis + " zoom:" + zoom);
            }

            //循环转换到PDF
            for (int i = 0; i < sourceList.size(); i++) {

                fileNo = Util.getGuid();

                //开始循环解析待转换任务
                id = sourceList.get(i).get("id");
                url = getProperty.get("NASPath") + sourceList.get(i).get("url").replace("/EliteHtml5MailService/", "");

                log.debug("循环解析待转换任务(" + i + "):" + " id:" + id + " url:" + url + " PDFTempPath:" + PDFTempPath + " fileNo:" + fileNo);
                TimeUnit.SECONDS.sleep(20);
                //准备检查链接是否可以下载到文件
                String nowURL = "";
                int StatusCode = 500;

                JSONObject tempMap = new JSONObject();
                // 将要处理主要信息插入Map
                tempMap.put("id", id);
                tempMap.put("url", url);

                //调用转换
                convPath = PDFTempPath + fileNo + "_Conv.pdf";
                tempMap.put("convPath", convPath);
                convResult = PDFHelper.convertPDF(url, convPath);
                tempMap.put("convResult", convResult);

                String combPath = "";
                if (ismark.equals("1")) {
                    //调用水印
                    markPath = PDFTempPath + fileNo + "_Mark.pdf";
                    tempMap.put("markPath", markPath);
                    if (convResult) {
                        markResult = PDFHelper.addPdfMark(convPath, markPath, markpic, x_axis, y_axis, zoom);
                    } else {
                        markResult = false;
                    }
                    tempMap.put("markResult", markResult);

                    if (markResult) {
                        combPath = markPath;
                    }

                } else {
                    if (convResult) {
                        combPath = convPath;
                    }
                }
                //将待合并任务插入到List
                log.debug("combPath:" + combPath);
                if (combPath != null && combPath.length() > 0) {
                    combinList.add(combPath);
                }

                // 将任务处理结果Map插入List
                reValue.add(tempMap);

            }

            //检查是否需要合并
            if (ismerge.equals("1")) {
                String combinPath = PDFTempPath + Util.getGuid() + "_Merge.pdf";
                combResult = PDFHelper.combinPdf(combinList, combinPath);

                if (combResult) {
                    reJson = "{\"code\":\"1\",\"message\":\"成功\",\"value\":\"" + combinPath + "\"}";

                    //将文件放入邮件服务中供客户端打开
                    try {
                        boolean copyResult = copyFile(combinPath, combinPath.replace(getProperty.get("NASPath"), getProperty.get("MAILPath")), true);
                        log.debug("Copy File to Nas Disk:" + copyResult);
                    } catch (Exception e) {
                        log.error("Copy File to Nas Disk Exception:", e);
                    }

                } else {
                    reJson = "{\"code\":\"1\",\"message\":\"合并失败\"}";
                }
            } else {
                reJson = "{\"code\":\"1\",\"message\":\"成功\",\"value\":" + reValue.toString() + "}";
            }

            log.debug("apiPDFDeal 接收返回Json:" + reJson);
            return reJson;

        } catch (Exception e) {

            log.error("apiPDFDeal Exception", e);
            reJson = "{\"code\":\"0\",\"message\":\"错误:" + e.getMessage() + "\"}";
            return reJson;
        }
    }


    public static boolean copyFile(String srcFileName, String destFileName, boolean overlay) {
        File srcFile = new File(srcFileName);

        if (!srcFile.exists()) {
            log.error("源文件：" + srcFileName + "不存在!");
            return false;
        }
        if (!srcFile.isFile()) {
            log.error("复制文件失败，源文件：" + srcFileName + "不是一个文件！");
            return false;
        }

        File destFile = new File(destFileName);
        if (destFile.exists()) {
            if (overlay) {
                new File(destFileName).delete();
            }

        } else if (!destFile.getParentFile().exists()) {
            if (!destFile.getParentFile().mkdirs()) {
                return false;
            }

        }

        int byteread = 0;
        InputStream inp = null;
        OutputStream out = null;
        try {
            inp = new FileInputStream(srcFile);
            out = new FileOutputStream(destFile);
            byte[] buffer = new byte[1024];
            while ((byteread = inp.read(buffer)) != -1) {
                out.write(buffer, 0, byteread);
            }
            return true;
        } catch (Exception e) {
            log.error(e);
            return false;
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (inp != null)
                    inp.close();
            }
            catch (IOException e) {
                log.error(e);
            }
        }
    }


}